package com.wolfpire.workflow.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.workflow.dao.WfTypeDao;
import com.wolfpire.workflow.om.WfType;

@Repository("wfTypeDao")
public class WfTypeDaoImpl extends BaseHibernateDao<WfType, Long> implements WfTypeDao {

	@SuppressWarnings("unchecked")
	public List<WfType> getWfTypeTree(String catKey) {
		Criteria criteria = createCriteria();
		criteria.add(Restrictions.eq("catKey", catKey));
		criteria.add(Restrictions.eq("parentId", 0L));
		return (List<WfType>)criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<WfType> getWfTypeTreeByPId(Long subls_pId) {
		Criteria criteria = createCriteria();
		criteria.add(Restrictions.eq("parentId", subls_pId));
		return (List<WfType>)criteria.list();
	}

	@Override
	public Page<WfType> findWfTypes(EasyuiPage<WfType> page, WfType filterWfType) {
		Criterion[] criterions = this.createFilter(filterWfType, null);
		int totalCount = this.findIntByCriteria(criterions);
		page.setTotalCount(totalCount);
		if (0 < totalCount) {
			Criteria c = createCriteria(criterions);
			c = setPageParameter(c, page);
			@SuppressWarnings("unchecked")
			List<WfType> wfTypes = c.list();
			page.setDataList(wfTypes);
		}
		return page;
	}

	private Criterion[] createFilter(WfType filterWfType, String type) {
		if (null == filterWfType) {
			return null;
		}
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (null != filterWfType.getId()) {
			criterions.add(Restrictions.eq("id", filterWfType.getId()));
		}
		if (null != filterWfType.getParentId()) {
			criterions.add(Restrictions.eq("parentId", filterWfType.getParentId()));
		}  else {
			if ("tree".equals(type)) {
				criterions.add(Restrictions.isNull("parentId"));
			}
		}
		if (!StringUtils.isBlank(filterWfType.getTypeName())) {
			criterions.add(Restrictions.like("typeName", filterWfType.getTypeName(), MatchMode.START));
		}
		return criterions.toArray(new Criterion[criterions.size()]);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WfType> list(WfType wfType) {
		Criteria criteria = createCriteria(this.createFilter(wfType, "tree"));
		return criteria.list();
	}

}
